// 管理员员工管理内容组件（占满宽度）
Vue.component('admin-employee-content', {
  data() {
    return {
      employees: [],
      dialogVisible: false,
      editEmployee: {
        id: '', name: '', gender: '', phone: '', department_id: '', position: ''
      },
      isEdit: false,
      searchQuery: '',
      selectedDepartment: '',
      departments: [],
      // 分页功能
      currentPage: 1,
      pageSize: 10,
      totalRecords: 0,
      loading: false
    };
  },
  methods: {
    // 获取部门名称的辅助方法
    getDepartmentName(departmentId) {
      const dept = this.departments.find(d => d.id === departmentId);
      return dept ? dept.name : '未知部门';
    },
    
    // 加载员工列表
    async loadEmployees() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          search: this.searchQuery || undefined,
          department_id: this.selectedDepartment || undefined
        };
        
        const response = await employeeAPI.getEmployees(params);
        this.employees = response.data.employees || [];
        this.totalRecords = response.data.total || 0;
      } catch (error) {
        console.error('加载员工列表失败:', error);
        this.$message.error('加载员工列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 加载部门列表
    async loadDepartments() {
      try {
        const response = await departmentAPI.getDepartments();
        this.departments = response.data.departments || [];
      } catch (error) {
        console.error('加载部门列表失败:', error);
        this.$message.error('加载部门列表失败');
      }
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.loadEmployees();
    },
    
    handleReset() {
      this.searchQuery = '';
      this.selectedDepartment = '';
      this.currentPage = 1;
      this.loadEmployees();
    },
    
    handlePageChange(page) {
      this.currentPage = page;
      this.loadEmployees();
    },
    
    openAddDialog() {
      this.isEdit = false;
      this.editEmployee = { id: '', name: '', gender: '', phone: '', department_id: '', position: '' };
      this.dialogVisible = true;
    },
    
    openEditDialog(row) {
      this.isEdit = true;
      this.editEmployee = Object.assign({}, row);
      this.dialogVisible = true;
    },
    
    async saveEmployee() {
      if (!this.editEmployee.name || !this.editEmployee.gender || !this.editEmployee.phone || !this.editEmployee.department_id || !this.editEmployee.position) {
        this.$message.error('请填写完整信息');
        return;
      }
      
      try {
        if (this.isEdit) {
          await employeeAPI.updateEmployee(this.editEmployee.id, this.editEmployee);
          this.$message.success('员工信息已更新');
        } else {
          await employeeAPI.createEmployee(this.editEmployee);
          this.$message.success('员工已添加');
          this.currentPage = 1;
        }
        this.dialogVisible = false;
        this.loadEmployees();
      } catch (error) {
        console.error('保存员工失败:', error);
        this.$message.error(error.message || '保存员工失败');
      }
    },
    
    async deleteEmployee(row) {
      this.$confirm('确定要删除该员工吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await employeeAPI.deleteEmployee(row.id);
          this.$message.success('员工已删除');
          
          // 删除后检查当前页是否还有数据
          const totalPages = Math.ceil((this.totalRecords - 1) / this.pageSize);
          if (this.currentPage > totalPages && totalPages > 0) {
            this.currentPage = totalPages;
          }
          
          this.loadEmployees();
        } catch (error) {
          console.error('删除员工失败:', error);
          this.$message.error(error.message || '删除员工失败');
        }
      });
    }
  },
  
  async mounted() {
    await this.loadDepartments();
    await this.loadEmployees();
  },
  
  template: `
    <div style="padding: 20px;">
      <el-card shadow="hover">
        <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">员工管理</div>
        
        <!-- 操作栏：搜索 + 添加按钮 -->
        <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-input 
              v-model="searchQuery" 
              placeholder="搜索姓名" 
              style="width: 150px;"
              size="small"
              clearable
            ></el-input>
            <el-select 
              v-model="selectedDepartment" 
              placeholder="选择部门" 
              style="width: 120px;"
              size="small"
              clearable
            >
              <el-option 
                v-for="dept in departments" 
                :key="dept.id" 
                :label="dept.name" 
                :value="dept.id"
              ></el-option>
            </el-select>
            <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
            <el-button size="small" @click="handleReset">重置</el-button>
          </div>
          <el-button type="primary" size="small" @click="openAddDialog">添加员工</el-button>
        </div>
        
        <!-- 表格占满宽度，去掉固定宽度限制 -->
        <el-table 
          :data="employees" 
          style="width: 100%;"
          border
          stripe
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="姓名" min-width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="phone" label="手机号" min-width="130"></el-table-column>
          <el-table-column label="部门" min-width="120">
            <template slot-scope="scope">
              {{ getDepartmentName(scope.row.department_id) }}
            </template>
          </el-table-column>
          <el-table-column prop="position" label="职位" min-width="120"></el-table-column>
          <el-table-column label="操作" min-width="180" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" @click="deleteEmployee(scope.row)" style="color: #F56C6C;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div style="margin: 18px 0 0; text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalRecords"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
        
        <el-dialog :title="isEdit ? '编辑员工' : '添加员工'" :visible.sync="dialogVisible" width="400px">
          <el-form :model="editEmployee" label-width="80px">
            <el-form-item label="姓名">
              <el-input v-model="editEmployee.name" placeholder="请输入姓名" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="editEmployee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="editEmployee.phone" placeholder="请输入手机号" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="部门">
              <el-select v-model="editEmployee.department_id" placeholder="请选择部门" style="width: 100%;">
                <el-option 
                  v-for="dept in departments" 
                  :key="dept.id" 
                  :label="dept.name" 
                  :value="dept.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职位">
              <el-input v-model="editEmployee.position" placeholder="请输入职位" style="width: 100%;"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveEmployee">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  `
});